import axios from 'axios';
import { ElMessage } from 'element-plus';
import { userState } from '../store/module/user';
import pinia from '../store';
const service = axios.create({
	baseURL: import.meta.env.VITE_APP_BASE_API,
	withCredentials: true,
	timeout: 6000000,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
		'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
	}
});
let loading;
//正在请求的数量
let requestCount = 0;
//显示loading
// const showLoading = () => {
// 	if (requestCount === 0) {
// 		loading = ElLoading.service({
// 			fullscreen: true,
// 			text: 'Loading  ',
// 			background: 'rgba(0, 0, 0, 0.7)'
// 		});
// 	}
// 	requestCount++;
// };
//隐藏loading
const hideLoading = () => {
	requestCount--;
	if (requestCount == 0) {
		loading.close();
	}
};

// 定义请求拦截器
service.interceptors.request.use(
	(config) => {
		const store = userState(pinia);
		const { token, tokenHead } = store;
		// 配置header
		if (token) {
			config.headers.Authorization = tokenHead + token;
		}
		return config;
	},
	(error) => {
		// 处理错误
		return Promise.reject(error);
	}
);
//响应拦截器
service.interceptors.response.use(
	(response) => {
		let { data } = response;
		if (data.code === 401) {
			ElMessage({
				message: data.message,
				type: 'error'
			});
		} else {
			return data;
		}
	},
	(error) => {
		hideLoading();
		//响应错误
		let message = '';
		if (error.response && error.response.status) {
			const status = error.response.status;
			switch (status) {
				case 400:
					message = '请求错误';
					break;
				case 401:
					message = '请求错误';
					break;
				case 404:
					message = '请求地址出错';
					break;
				case 408:
					message = '请求超时';
					break;
				case 500:
					message = '服务器内部错误!';
					break;
				case 501:
					message = '服务未实现!';
					break;
				case 502:
					message = '网关错误!';
					break;
				case 503:
					message = '服务不可用!';
					break;
				case 504:
					message = '网关超时!';
					break;
				case 505:
					message = 'HTTP版本不受支持';
					break;
				default:
					message = '请求失败';
			}
			ElMessage.error(message);
		}
		return Promise.reject(error);
	}
);

export default service;
